package com.snail.utils;
import java.util.ArrayList;
import java.util.List;
import org.commonmark.node.*;
import org.commonmark.parser.Parser;
import java.util.ArrayList;
import java.util.List;

/**
 * @author ysc
 * @descrpiton 提取mark的关键内容
 * @date 2025/7/19 16:13
 **/
public class TextSplitter {
    /**
     * 将 Markdown 内容解析为多个逻辑段（段落、列表项等），去除 Markdown 格式，仅保留纯文本
     */
    public static List<String> splitMarkdown(String markdown) {
        List<String> chunks = new ArrayList<>();
        Parser parser = Parser.builder().build();
        Node document = parser.parse(markdown);

        collectChunks(document, chunks);
        return chunks;
    }

    /**
     * 遍历 Markdown AST，将段落、标题、列表项作为独立切片
     */
    private static void collectChunks(Node node, List<String> chunks) {
        for (Node current = node.getFirstChild(); current != null; current = current.getNext()) {
            if (current instanceof Paragraph ||
                    current instanceof Heading ||
                    current instanceof ListItem ||
                    current instanceof BlockQuote) {
                String text = extractText(current).trim();
                if (!text.isEmpty()) {
                    chunks.add(text);
                }
            } else if (current instanceof BulletList || current instanceof OrderedList) {
                collectChunks(current, chunks);
            } else {
                collectChunks(current, chunks); // 深度遍历其它容器类型
            }
        }
    }

    /**
     * 提取某个 Node 中的纯文本内容（忽略格式）
     */
    private static String extractText(Node node) {
        StringBuilder sb = new StringBuilder();

        node.accept(new AbstractVisitor() {
            @Override
            public void visit(Text text) {
                sb.append(text.getLiteral());
            }

            @Override
            public void visit(SoftLineBreak softLineBreak) {
                sb.append(' ');
            }

            @Override
            public void visit(HardLineBreak hardLineBreak) {
                sb.append(' ');
            }

            @Override
            public void visit(Code code) {
                sb.append(code.getLiteral());
            }

            @Override
            public void visit(StrongEmphasis strongEmphasis) {
                visitChildren(strongEmphasis);
            }

            @Override
            public void visit(Emphasis emphasis) {
                visitChildren(emphasis);
            }

            @Override
            public void visit(Link link) {
                visitChildren(link); // 忽略 URL，仅提取文字
            }


            public void visit(Node node) {
                visitChildren(node); // 默认行为：递归子节点
            }
        });

        return sb.toString();
    }
    /**
     * 提取 Markdown 中的所有标题（Heading 节点内容）
     */
    public static List<String> extractHeadings(String markdown) {
        List<String> headings = new ArrayList<>();
        Parser parser = Parser.builder().build();
        Node document = parser.parse(markdown);

        document.accept(new org.commonmark.node.AbstractVisitor() {
            @Override
            public void visit(Heading heading) {
                StringBuilder sb = new StringBuilder();
                for (Node node = heading.getFirstChild(); node != null; node = node.getNext()) {
                    if (node instanceof Text) {
                        sb.append(((Text) node).getLiteral());
                    }
                }
                headings.add(sb.toString().trim());
                // 不要忘记继续遍历其他节点
                visitChildren(heading);
            }
        });

        return headings;
    }
}
